<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Menu;
use App\Models\User;
use App\Models\Role;

class MenuController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $data = (new Menu)->buildTree();
        $responseJson = [
            'code' => 200,
            'message' => '',
            'data' => $data
        ];
        return response()->json($responseJson);
    }

    /**
     * @param Request $request
     * @return void
     */
    public function loginMenu(Request $request)
    {
        $user = auth()->user(); // 获取当前登录用户的对象
        $permissions = $user->getAllPermissions()->pluck('name');
        $menus = $user->getAllPermissions();
        $menusWithChild = $this->buildMenus($menus, 0);
        $homemenu = [  //默认加入home
            "name" => "home",
            "path" => "/home",
            "meta" => [
                "title" => "首页",
                "icon" => "el-icon-eleme-filled",
                "type" => "menu"
            ],
            "children" => [
                [
                    "name" => "dashboard",
                    "path" => "/dashboard",
                    "meta" => [
                        "title" => "控制台",
                        "icon" => "el-icon-menu",
                        "affix" => true
                    ],
                    "component" => "home"
                ],
                [
                    "name" => "userCenter",
                    "path" => "/usercenter",
                    "meta" => [
                        "title" => "帐号信息",
                        "icon" => "el-icon-user",
                        "tag" => "NEW"
                    ],
                    "component" => "userCenter"
                ]
            ]
        ];
        $about = [
            "path" => "/other/about",
            "name" => "about",
            "meta" => [
                "title" => "关于",
                "icon" => "el-icon-info-filled",
                "type" => "menu"
            ],
            "component" => "other/about"
        ];
        // 合并数组
        $mergedMenus = array_merge([$homemenu], $menusWithChild, [$about]);
        $data = [
            'menu' => $mergedMenus,
            'permissions' => $permissions
        ];
        $return = [
            'code' => 200,
            'message' => '',
            'data' => $data
        ];
        return response()->json($return);
    }

    /**
     * @return void 创建层级的菜单
     */
    protected function buildMenus($menus, $pid = 0)
    {
        $result = [];
        foreach ($menus as $menu) {
            if ($menu->parentId  == $pid) {
                $children = $this->buildMenus($menus, $menu->id);
                if (!empty($children)) {  // 到达最后一层叶子节点时候，防止依附在children上
                    $menu->children = $children;
                }
                //以下这行是关键的一行，代表把这一个层级的所有菜单数据装进$result数组，由于开头处已经清空了result，所以这个result有且仅有这一个层级的数据
                $result[] = $menu;
            }
        }
        //最后返回，由上一层级的$children属性接受
        return $result;
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $validatedData = $request->validate([
            'id' => 'nullable|integer',
            'parentId' =>'nullable|integer',
            'name' => 'required|string|max:255',
            'path' => 'nullable',
            'component' => 'nullable',
            'meta' => 'required',
            'meta.type' => 'required|string|in:menu,iframe,link,button',//4种菜单类型
            'redirect' => 'nullable',
            'apiList' => 'nullable',
        ]);
        $validatedData['parentId'] = $validatedData['parentId'] ?? 0;
        $validatedData['path'] = $validatedData['path'] ?? '';
        $validatedData['component'] = $validatedData['component'] ?? '';
        $validatedData['redirect'] = $validatedData['redirect'] ?? '';
        $validatedData['apiList'] = $validatedData['apiList'] ?? [];
        if (empty($validatedData['id'])) { //新增
            $menu = Menu::create($validatedData);
        } else { //更新
            $menu = Menu::findOrFail($validatedData['id']);
            $menu->update($validatedData);
        }
        $responseJson = [
            'code' => 200,
            'message' => '',
            'data' => $menu->id
        ];
        return response()->json($responseJson);
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
        //return Menu::find($id);
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {

    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($ids)
    {
        if (strpos($ids, ',') !== false) {
            $numbers = explode(',', $ids);
            foreach ($numbers as $num) {
                $menu = Menu::findOrFail($num);
                $menu->delete();
            }
        } else {
            $menu = Menu::findOrFail($ids);
            $menu->delete();
        }
        $responseJson = [
            'code' => 200,
            'message' => '成功删除',
        ];
        return response()->json($responseJson);
    }
}
